package handler

import (
	"2302a/testyuekao/api/request"
	"2302a/testyuekao/api/resp"
	"2302a/testyuekao/consts"
	"2302a/testyuekao/internal/dao"
	"2302a/testyuekao/internal/model"
	"2302a/testyuekao/pkg"
	"fmt"
	"github.com/gin-gonic/gin"
	"time"
)

func UserRegister(c *gin.Context) {
	var req request.UserRegisterReq

	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 100000, "参数信息错误", err.Error())
		return
	}
	var user model.Users
	dao.GetOneByFields(&model.Users{Mobile: req.Mobile}, &user)
	if user.Id > 0 {
		resp.Error(c, 100002, "用户已存在", nil)
		return
	}
	release := model.Users{
		Mobile:   req.Mobile,
		Password: pkg.Md5Encryption(req.Password),
		UType:    req.UType,
	}
	dao.Create(&release)
	if pkg.Md5Encryption(req.Password) != pkg.Md5Encryption(req.Confirm) {
		resp.Error(c, 100003, "两个密码不一致", nil)
		return
	}
	resp.Success(c, "注册成功", true)
}

func UserLogin(c *gin.Context) {
	var req request.UserLoginReq

	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 100000, "参数信息错误", err.Error())
		return
	}
	var user model.Users
	dao.GetOneByFields(&model.Users{Mobile: req.Mobile}, &user)
	if user.Id == 0 {
		resp.Error(c, 100002, "用户不存在", nil)
		return
	}
	fmt.Println(user.Id)
	//	if !(user.UType == 1 || user.UType == 3) {
	//		resp.Error(c, 100003, "用户类型错误", nil)
	//		return
	//	}
	if pkg.Md5Encryption(req.Password) != pkg.Md5Encryption(req.Confirm) {
		resp.Error(c, 100004, "账号或者密码错误", nil)
		return
	}
	token := pkg.CreateJwtToken(user.Id, user.UType, 24*time.Hour, consts.JWT_KEY)
	resp.Success(c, "登录成功", token)
}

func RefreshToken(c *gin.Context) {
	var user model.Users
	userId := c.GetUint("userId")
	refreshToken := pkg.CreateJwtToken(userId, user.UType, 24*3*time.Hour, consts.JWT_KEY)
	resp.Success(c, "刷新token成功", refreshToken)
}
